﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;

namespace monitor_server
{
    public delegate void form8enable(bool a, dev_add b);
    public delegate void form10enable(bool a);
    public partial class Form7 : Form
    {
        dev_add dev = new dev_add();
        bool f8 = false;
        bool f10 = false;
        //bool tree_file = false;                                         //false - основной файл, true - временный
        formenable d;
        string[] read_tree;
        string[] oblast = new string[6];
        string[] oblast_t = new string[6];


        public Form7(formenable sender)
        {
            InitializeComponent();
            d = sender;
        }

        void func8(bool param, dev_add opt)
        {
            f8 = param;
            dev = opt;
        }

        void func10(bool param)
        {
            f10 = param;
        }

        private void выходToolStripMenuItem_Click(object sender, EventArgs e)
        {
            DialogResult res;
            res = System.Windows.Forms.MessageBox.Show("Вы действительно хотите выйти?\r\nВсе несохраненные данные будут потеряны.", "", MessageBoxButtons.OKCancel);
            if (res == DialogResult.Cancel)
                return;
            for (int i = 0; i < 6; i++)
            {
                File.Delete(@"resources\maps\" + oblast[i] + ".ini");
                File.Copy(@"resources\maps\" + oblast[i] + "_t1.ini", @"resources\maps\" + oblast[i] + ".ini");
                File.Delete(@"resources\maps\" + oblast[i] + "_t1.ini");
            }
            d(false);
            this.Close();
        }

        private void Form7_Load(object sender, EventArgs e)
        {
            
        }

        private void tree_update(bool tree_file)
        {
            //Чтение файла и построение дерева.
            treeView1.Nodes.Clear();
            
            int i = 0, obn = 0, count = -1, blr_num = 0, blr_count;
            int u = 0, u1 = 0, t = 0;
            string[] blr_write = new string[1];
            string dev = "", node_text = "", ipstr = "", blr = "", obl = "";
            TreeNode[,] devices = new TreeNode[2, 6];
            
            treeView1.BeginUpdate();
            for (obn = 0; obn < 6; obn++)
            {
                t = 0;
                FileStream fs;
                while (true)
                {
                    try
                    {
                        fs = new FileStream(@"resources\blr_tmp", FileMode.Create, FileAccess.ReadWrite);
                        break;
                    }
                    catch (UnauthorizedAccessException)
                    {
                        //хероватое дело
                    }
                }

                blr_count = 0;
                count = -1;
                i = 0;
                try
                {
                    if (!tree_file)
                        read_tree = File.ReadAllLines(@"resources\maps\" + oblast[obn] + ".ini", Encoding.GetEncoding("Windows-1251"));
                    else
                        read_tree = File.ReadAllLines(@"resources\maps\" + oblast_t[obn] + ".ini", Encoding.GetEncoding("Windows-1251"));
                    if (read_tree.Length == 0)
                    {
                        if (!tree_file)
                            MessageBox.Show("Файл " + oblast[obn] + ".ini поврежден");
                        else
                            MessageBox.Show("Файл " + oblast_t[obn] + ".ini поврежден");
                        fs.Close();
                        d(false);
                        this.Close();
                        return;                        
                    }
                }                
                catch(Exception)
                {
                    fs.Close();
                    d(false);
                    this.Close();
                    return;
                }
                while (i < read_tree.Length)
                {
                    switch (read_tree[i])
                    {
                        case "[Измерители]":
                            count++;
                            dev = "izm";
                            devices[count, obn] = new TreeNode();
                            devices[count, obn].Text = "Измерители";
                            i++;
                            break;
                        case "[Анализаторы]":
                            count++;
                            dev = "anal";
                            devices[count, obn] = new TreeNode();
                            devices[count, obn].Text = "Анализаторы";
                            i++;
                            break;
                        case "":
                            i++;
                            break;
                        default:
                            u = 0; u1 = 0;
                            while (read_tree[i][u] != '=')
                                u++;
                            node_text = read_tree[i].Substring(0, u);
                            u++;
                            ipstr = read_tree[i].Substring(u, read_tree[i].Length - u);
                            if (dev == "izm")
                            {
                                u1 = u;
                                while (read_tree[i][u1] != ',')
                                    u1++;
                                ipstr = read_tree[i].Substring(u, u1 - u);
                                u1++;
                                while (read_tree[i].Substring(u, 3) != "BLR")
                                    u++;
                                try
                                {
                                    blr = read_tree[i].Substring(u, 5);
                                }
                                catch (ArgumentOutOfRangeException)
                                {
                                    blr = read_tree[i].Substring(u, 4);
                                }                                
                                if (blr_count == 0)
                                {
                                    byte[] bt = new byte[7];
                                    bt[0] = (byte)blr[0];
                                    bt[1] = (byte)blr[1];
                                    bt[2] = (byte)blr[2];
                                    bt[3] = (byte)blr[3];
                                    bt[4] = (byte)blr[4];
                                    bt[5] = (byte)blr_count;
                                    bt[6] = (byte)'\n';
                                    fs.Write(bt, 0, 7);
                                    devices[count, obn].Nodes.Add(blr);
                                    blr_num = t;
                                    blr_count++;
                                    //devices[count, obn].Nodes.Add(blr);
                                }
                                else
                                {

                                    string[] str = new string[blr_count];
                                    fs.Close();
                                    str = File.ReadAllLines(@"resources\blr_tmp");
                                    //fs = new FileStream(@"resources\blr_tmp", FileMode.Open, FileAccess.ReadWrite);
                                    fs = new FileStream(@"resources\blr_tmp", FileMode.Append, FileAccess.Write);
                                    for (t = 0; t < blr_count; t++)
                                    {
                                        if (str[t].Substring(0, 5).Equals(blr))
                                            break;
                                    }
                                    if (t == blr_count)
                                    {
                                        byte[] bt = new byte[7];
                                        bt[0] = (byte)blr[0];
                                        bt[1] = (byte)blr[1];
                                        bt[2] = (byte)blr[2];
                                        bt[3] = (byte)blr[3];
                                        bt[4] = (byte)blr[4];
                                        bt[5] = (byte)blr_count;
                                        bt[6] = (byte)'\n';
                                        fs.Write(bt, 0, 7);                                        
                                        blr_num = t;
                                        blr_count++;
                                        devices[count, obn].Nodes.Add(blr);
                                    }
                                    else
                                    {
                                        blr_num = t;
                                        //devices[count, obn].Nodes.Add(blr);                                        
                                    }
                                }
                                //-------------------------------
                                u = 1;
                                //-------------------------------
                                //devices[count,obn].Nodes.Add(node_text).Tag = ipstr;
                                devices[count, obn].Nodes[blr_num].Nodes.Add(node_text).Tag = ipstr;
                            }
                            else
                                devices[count, obn].Nodes.Add(node_text).Tag = ipstr;
                            i++;
                            break;
                    }
                }
                if(!tree_file)
                    switch (oblast[obn])
                    {
                        /*case "Brest":
                            obl = "Брест";
                            break;
                        case "Vitebsk":
                            obl = "Витебск";
                            break;
                        case "Gomel":
                            obl = "Гомель";
                            break;
                        case "Grodno":
                            obl = "Гродно";
                            break;
                        case "Minsk":
                            obl = "Минск";
                            break;
                        case "Mogilev":
                            obl = "Могилев";
                            break;*/
                        case "Brest":
                            obl = "Брестская";
                            break;
                        case "Vitebsk":
                            obl = "Витебская";
                            break;
                        case "Gomel":
                            obl = "Гомельская";
                            break;
                        case "Grodno":
                            obl = "Гродненская";
                            break;
                        case "Minsk":
                            obl = "Минская";
                            break;
                        case "Mogilev":
                            obl = "Могилевская";
                            break;
                    }
                else
                    switch (oblast_t[obn])
                {
                    /*case "Brest_t":
                        obl = "Брест";
                        break;
                    case "Vitebsk_t":
                        obl = "Витебск";
                        break;
                    case "Gomel_t":
                        obl = "Гомель";
                        break;
                    case "Grodno_t":
                        obl = "Гродно";
                        break;
                    case "Minsk_t":
                        obl = "Минск";
                        break;
                    case "Mogilev_t":
                        obl = "Могилев";
                        break;*/
                    case "Brest_t":
                        obl = "Брестская";
                        break;
                    case "Vitebsk_t":
                        obl = "Витебская";
                        break;
                    case "Gomel_t":
                        obl = "Гомельская";
                        break;
                    case "Grodno_t":
                        obl = "Гродненская";
                        break;
                    case "Minsk_t":
                        obl = "Минская";
                        break;
                    case "Mogilev_t":
                        obl = "Могилевская";
                        break;
                }
                treeView1.Nodes.Add(obl);
                TreeNode[] n1 = new TreeNode[2];
                n1[0] = devices[0, obn];
                n1[1] = devices[1, obn];                
                treeView1.Nodes[obn].Nodes.AddRange(n1);
                fs.Close();
                File.Delete(@"resources\blr_tmp");

            }
            treeView1.ExpandAll();
            treeView1.EndUpdate();
        }

        private void Form7_Shown(object sender, EventArgs e)
        {
            
            oblast[0] = "Brest";
            oblast[1] = "Gomel";
            oblast[2] = "Grodno";
            oblast[3] = "Minsk";
            oblast[4] = "Mogilev";
            oblast[5] = "Vitebsk";
            oblast_t[0] = "Brest_t";
            oblast_t[1] = "Gomel_t";
            oblast_t[2] = "Grodno_t";
            oblast_t[3] = "Minsk_t";
            oblast_t[4] = "Mogilev_t";
            oblast_t[5] = "Vitebsk_t";
            
            for (int i = 0; i < 6; i++)
            {
                if (File.Exists(@"resources\maps\" + oblast[i] + "_t1.ini"))
                    File.Delete(@"resources\maps\" + oblast[i] + "_t1.ini");
                if (File.Exists(@"resources\maps\" + oblast[i] + "_t.ini"))
                    File.Delete(@"resources\maps\" + oblast[i] + "_t.ini");
            }
            tree_update(false);
            for (int i = 0; i < 6; i++)
            {
                try
                {
                    File.Copy(@"resources\maps\" + oblast[i] + ".ini", @"resources\maps\" + oblast[i] + "_t1.ini");
                }
                catch (Exception)
                {
                    MessageBox.Show("Файл " + oblast[i] + ".ini поврежден.");
                    this.Close();
                    return;
                }
            }
        }
        
        private void treeView1_NodeMouseDoubleClick(object sender, TreeNodeMouseClickEventArgs e)
        {
            int type = -1; // 0 - анлизатор, 1 - измеритель
            string obl = "";
            string[] read_tree;
            string rtps = "";            
            try
            {                
                if (e.Node.Text.Equals("Измерители"))
                {
                    if (!File.Exists(@"resources\izmers.csv"))
                    {
                        MessageBox.Show("Файл izmers.csv не существует.");
                        return;
                    }
                    else
                    {
                        obl = e.Node.Parent.Text;
                        if (!f10)
                        {
                            f10 = true;                            
                            Form10 form10 = new Form10(new form10enable(func10), obl, e.Node);
                            form10.Owner = this;
                            form10.Enabled = false;
                            form10.Show();
                        }
                    }
                    if (e.Node.IsExpanded)
                        e.Node.Collapse();
                    else e.Node.Expand();
                    return;                    
                }
                else if (e.Node.Parent.Parent.Text.Equals("Измерители") || e.Node.Parent.Text.Equals("Анализаторы"))
                {
                    if (e.Node.Parent.Parent.Text.Equals("Измерители"))
                        type = 1;
                    else if (e.Node.Parent.Text.Equals("Анализаторы"))
                        type = 0;
                }
                else return;
            }
            catch (NullReferenceException)
            {
                return;
            }
            if (type == -1)
            {
                MessageBox.Show("WTF?!");
                return;
            }
            rtps = e.Node.Text;
            if (type == 1)
            {
                obl = e.Node.Parent.Parent.Parent.Text;
            }
            else if (type == 0)
                obl = e.Node.Parent.Parent.Text;
            switch (obl)
            {
                case "Брестская":
                    obl = "Brest";
                    break;
                case "Витебская":
                    obl = "Vitebsk";
                    break;
                case "Гомельская":
                    obl = "Gomel";
                    break;
                case "Гродненская":
                    obl = "Grodno";
                    break;
                case "Минская":
                    obl = "Minsk";
                    break;
                case "Могилевская":
                    obl = "Mogilev";
                    break;
            }
            read_tree = File.ReadAllLines(@"resources\maps\" + obl + ".ini", Encoding.GetEncoding("Windows-1251"));
            //--------------------------------Редактирование-----------------------------------------------------
            dev_add devi = new dev_add();
            devi.mod = true;
            devi.obl = obl;
            devi.name = rtps;            
            devi.ip = e.Node.Tag.ToString();
            devi.type = type;
            if (devi.type == 1)
            {
                devi.blr = e.Node.Parent.Text;
            }
            int izmStartNum = 0;
            for (int i = 0; i < read_tree.Length; i++)
                if (read_tree[i] == "[Измерители]")
                    izmStartNum = i + 1;
            if (devi.type == 1)
            {
                for (int i = izmStartNum; i < read_tree.Length; i++)
                {
                    try
                    {
                        if (devi.name == read_tree[i].Substring(0, devi.name.Length))
                        {
                            if (read_tree[i].Substring(read_tree[i].Length - 2, 2) == ",0")
                                devi.take_params = false;
                            else if (read_tree[i].Substring(read_tree[i].Length - 2, 2) == ",1")
                                devi.take_params = true;
                            else
                                MessageBox.Show("Параметр take_param для измерителя " + devi.name + " не установлен.");
                        }
                    }
                    catch (ArgumentException)
                    {
                        continue;
                    }
                }
            }

            if (!f8)
            {
                f8 = true;
                Form8 form8 = new Form8(new form8enable(func8), devi);
                form8.Owner = this;
                form8.Show();
                form8.FormClosed += new FormClosedEventHandler(form8_FormClosed);
            }
            //-----------------------------------Удаление Объекта---------------------------------------------------
            /*    
            for (i = 0; i < 6; i++)
            {
                if (oblast[i] != obl)
                {
                    File.Copy(@"resources\maps\" + oblast[i] + ".ini", @"resources\maps\" + oblast[i] + "_t.ini");
                }
            }
            StreamWriter sw = new StreamWriter(@"resources\maps\" + obl + "_t.ini", false, Encoding.GetEncoding("Windows-1251"));
            for (i = 0; i < read_tree.Length; i++)
            {
                if (read_tree[i] == "[Анализаторы]")
                    dev1 = false;
                if (read_tree[i] == "[Измерители]")
                    dev1 = true;
                //  read_tree[i].Substring(rtps.Length, 1) == "="
                try
                {
                    //------------------Если проблемы с сохранением списка устройств, смотреть сюда
                    if ((read_tree[i].Substring(0, rtps.Length) != rtps) || (dev1 != dev) || (read_tree[i].Substring(rtps.Length, 1) != "="))
                        sw.WriteLine(read_tree[i]);
                }
                catch(ArgumentOutOfRangeException)
                {
                    sw.WriteLine(read_tree[i]);
                }
            }
            sw.Close();
            tree_update(true);
            for (i = 0; i < 6; i++)
            {
                File.Delete(@"resources\maps\" + oblast[i] + ".ini");
                File.Copy(@"resources\maps\" + oblast[i] + "_t.ini", @"resources\maps\" + oblast[i] + ".ini");
                File.Delete(@"resources\maps\" + oblast[i] + "_t.ini");
            }
            */
            //-----------------------------------------------------------------------------------------------
        }

        private void добавитьУстройствоToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if(!f8)
            {
                f8 = true;
                dev_add devi = new dev_add();
                devi.mod = false;
                devi.del = false;
                devi.cancel = false;
                Form8 form8 = new Form8(new form8enable(func8), devi);
                form8.Owner = this;
                form8.Show();                
                form8.FormClosed += new FormClosedEventHandler(form8_FormClosed);
            }
        }

        void form8_FormClosed(object sender, FormClosedEventArgs e)
        {
            if (!dev.cancel)
            {
                int i;             
                    if (!dev.del)                               //Добавление объекта
                    {
                        string except_obl = "";
                        //throw new NotImplementedException();                        
                        except_obl = dev.obl;
                        if (except_obl == "")
                            return;
                        string[] file = new string[2];
                        if(!dev.mod)
                            file = File.ReadAllLines(@"resources\maps\" + except_obl + ".ini", Encoding.GetEncoding("Windows-1251"));
                        else
                            file = File.ReadAllLines(@"resources\maps\" + except_obl + "_t.ini", Encoding.GetEncoding("Windows-1251"));
                        StreamWriter sw;
                        if(!dev.mod)
                            sw = new StreamWriter(@"resources\maps\" + except_obl + ".ini", false, Encoding.GetEncoding("Windows-1251"));
                        else
                            sw = new StreamWriter(@"resources\maps\" + except_obl + "_t.ini", false, Encoding.GetEncoding("Windows-1251"));
                        for (i = 0; i < file.Length; i++)
                        {
                            sw.WriteLine(file[i]);
                            if (dev.type == 1)
                            {
                                if (file[i] == "[Измерители]")
                                {
                                    string str = "";
                                    if (dev.take_params)
                                        str = ",1\r\n";
                                    else
                                        str = ",0\r\n";

                                    sw.WriteLine(dev.name + "=" + dev.ip + "," + dev.blr + str);
                                }
                            }
                            else if (dev.type == 0)
                            {
                                if (file[i] == "[Анализаторы]")
                                {
                                    sw.WriteLine(dev.name + "=" + dev.ip + "\r\n");
                                }
                            }
                        }
                        sw.Close();
                    }
                    if (!dev.mod)
                        tree_update(false);
                    else
                    {
                        tree_update(true);
                        for (i = 0; i < 6; i++)
                        {
                            File.Delete(@"resources\maps\" + oblast[i] + ".ini");
                            File.Copy(@"resources\maps\" + oblast[i] + "_t.ini", @"resources\maps\" + oblast[i] + ".ini");
                            File.Delete(@"resources\maps\" + oblast[i] + "_t.ini");
                        }
                    }
            }
        }

        private void сохранитьToolStripMenuItem_Click(object sender, EventArgs e)
        {
            for (int i = 0; i < 6; i++)
            {
                File.Delete(@"resources\maps\" + oblast[i] + "_t1.ini");
                File.Copy(@"resources\maps\" + oblast[i] + ".ini", @"resources\maps\" + oblast[i] + "_t1.ini");
                //File.Delete(@"resources\maps\" + oblast[i] + ".ini");
            }
            Izmers.createIzmersList();
            MessageBox.Show("Сохранение успешно завершено");
        }
        
    }
    
}
